package com.example.messageproducer;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

import javax.jms.*;

public class ProducerWithTransaction {

    private static final String BROKER_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "queue2";

    @Test
    public void testSendMessageToQueueWithTransaction() throws JMSException {

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
        Connection connection = connectionFactory.createConnection();

        // transacted用于指示Session是否是事务性的
        final boolean transacted = true;
        Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        Queue queue = session.createQueue(QUEUE_NAME);
        MessageProducer producer = session.createProducer(queue);

        for (int i = 0; i < 4; i++){
            TextMessage textMessage = session.createTextMessage("啊啊啊 ～～～～～～～～～～～～" + i);
            producer.send(textMessage);
        }


        // 提交所有在该事务中完成的消息，释放任何当前持有的锁。
        // 只要不提交事务，消息的消费者就不会看到这个事务中发送的消息
        session.commit();

        producer.close();
        session.close();
        connection.close();
    }
}
